const Dept = require('../models/Dept');

exports.createDept = async (req, res) => {
    try {
        const { parentId } = req.body;
        const ancestors = [];

        // 如果有父级部门，获取其祖先路径
        if (parentId) {
            const parentDept = await Dept.findById(parentId);
            if (parentDept) {
                ancestors.push(...parentDept.ancestors, parentId);
            }
        }

        const dept = new Dept({
            ...req.body,
            ancestors,
        });
        await dept.save();
        res.json(dept);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

exports.getDepts = async (req, res) => {
    try {
        const depts = await Dept.find(); // 获取所有部门
        res.json(depts);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

exports.getDeptPage = async (req, res) => {
    try {
        const { page = 1, limit = 10 } = req.query;
        const skip = (page - 1) * limit;

        const depts = await Dept.find()
            .skip(skip)
            .limit(limit);

        const totalDepts = await Dept.countDocuments();

        res.json({
            depts,
            currentPage: page,
            totalPages: Math.ceil(totalDepts / limit),
            totalDepts
        });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

exports.getDeptById = async (req, res) => {
    try {
        const dept = await Dept.findById(req.params.id);
        if (!dept) {
            return res.status(404).json({ message: '部门未找到' });
        }
        res.json(dept);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

exports.updateDept = async (req, res) => {
    try {
        const { parentId } = req.body;
        const ancestors = [];

        if (parentId) {
            const parentDept = await Dept.findById(parentId);
            if (parentDept) {
                ancestors.push(...parentDept.ancestors, parentId);
            }
        }

        const dept = await Dept.findByIdAndUpdate(req.params.id, {
            ...req.body,
            ancestors
        }, { new: true });
        if (!dept) {
            return res.status(404).json({ message: '部门未找到' });
        }
        res.json(dept);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

exports.deleteDept = async (req, res) => {
    try {
        const dept = await Dept.findByIdAndDelete(req.params.id);
        if (!dept) {
            return res.status(404).json({ message: '部门未找到' });
        }
        res.json({ message: '部门删除成功' });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};